#ifndef TETRIXBOARD_H
#define TETRIXBOARD_H

#include"tetrixpiece.h"

#include <QFrame>
#include<QBasicTimer>
#include<QPointer>

class QLabel;
class QPaintEvent;
class QKeyEvent;
class QTimerEvent;

const int BoardWidth=10;
const int BoardHeight=22;

class TetrixBoard : public QFrame
{
    Q_OBJECT
public:
    TetrixBoard(QWidget* parent=nullptr);

public:
    void setNextPieceLabe(QLabel* label);
    QSize sizeHint()const override;
    QSize minimumSizeHint()const override;

signals:
    void scoreChanged(int score);

public slots:
    void start();
    void pause();

protected:
    void paintEvent(QPaintEvent* event)override;
    void keyPressEvent(QKeyEvent* event)override;
    void timerEvent(QTimerEvent* event)override;

private:
    TetrixShape& shapeAt(int x,int y){return board[y*BoardWidth+x];}
    int squareWidth(){return this->contentsRect().width()/BoardWidth;}
    int squareHeight(){return this->contentsRect().height()/BoardHeight;}
    void clearBoard();
    void newPiece();
    void drawSquare(QPainter& painter,int x,int y,TetrixShape shape);
    bool tryMove(const TetrixPiece& newPiece,int newX,int newY);
    void dropDown();
    void oneLineDown();
    void pieceDropped(int h);
    void removeFullLines();
    void showNextPiece();

private:
    QBasicTimer timer;
    QPointer<QLabel> next_piece_labe;
    bool is_started;
    bool is_pause;
    bool is_wait_after_line;
    TetrixPiece cur_piece;
    TetrixPiece next_piece;
    int cur_x;
    int cur_y;
    int score;
    TetrixShape board[BoardWidth*BoardHeight];

};

#endif // TETRIXBOARD_H
